package models

import (
	"github.com/rs/xid"
)

// Customer 客户信息
type Customer struct {
	CustomerID   string `gorm:"primary_key"`
	Name         string `gorm:"size:255;not null"`
	Tel          string
	Manager      string `gorm:"not null"`
	Address      string
	WeiXin       string
	QQ           string
	EmailAddress string
}

// CreateCustomer 创建客户
func CreateCustomer(customer *Customer) error {
	customer.CustomerID = xid.New().String()

	tx := db.Begin()

	err := tx.Table("customers").Create(customer).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// DeleteCustomer 删除客户
func DeleteCustomer(customerID string) error {
	tx := db.Begin()
	err := tx.Table("customers").Where("customer_id = ?", customerID).Delete(Customer{}).Error
	if err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}

// UpdateCustomer 更新客户信息
func UpdateCustomer(customerID string, newName, newTel, newManager, newAddress, newWeiXin, newQQ, newEmailAddress string) error {
	customer := Customer{
		CustomerID:   customerID,
		Name:         newName,
		Tel:          newTel,
		Manager:      newManager,
		WeiXin:       newWeiXin,
		QQ:           newQQ,
		Address:      newAddress,
		EmailAddress: newEmailAddress,
	}
	return db.Table("customers").Table("customers").Where("customer_id = ?", customerID).Updates(customer).Error
}

// ListCustomers 所有客户
func ListCustomers() (customers []Customer, err error) {
	err = db.Table("customers").Table("customers").Select("customer_id, name, tel, manager,wei_xin,qq, address,email_address").Find(&customers).Error
	return
}

// GetCustomer 获取客户信息
func GetCustomer(customerID string) *Customer {
	var customer Customer
	db.Table("customers").Where("customer_id = ?", customerID).Select("customer_id, name, tel, manager,wei_xin,qq, address,email_address").First(&customer)
	return &customer
}

// HaveCustomerName 查询是否有此客户
func HaveCustomerName(name string) bool {
	return !db.Table("customers").Where("name = ?", name).First(&Customer{}).RecordNotFound()
}

// HaveCustomer 查询是否有此客户
func HaveCustomer(customerID string) bool {
	return !db.Table("customers").Where("customer_id = ?", customerID).First(&Customer{}).RecordNotFound()
}
